import React, { useEffect, useState } from 'react';
import {
  AreaChartOutlined,
  DashboardOutlined,
  FileTextOutlined,
  HomeOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MonitorOutlined,
  ProductOutlined,
  SmileOutlined,
  UserSwitchOutlined,
} from '@ant-design/icons';
import { Avatar, Button, Dropdown, Flex, Layout, Menu, MenuProps, message, Space, theme } from 'antd';
import { Outlet, useModel,history } from 'umi';
import staticMenuList from '../../config/menu';

const iconMap: { [key: string]: JSX.Element } = {
  smile: <SmileOutlined />,
  HomeOutlined: <HomeOutlined />,
  DashboardOutlined: <DashboardOutlined />,
  AreaChartOutlined: <AreaChartOutlined />,
  ProductOutlined: <ProductOutlined />,
  FileTextOutlined: <FileTextOutlined />,
  MonitorOutlined: <MonitorOutlined />,
  // 添加其他图标映射
};

const { Header, Sider, Content } = Layout;

const BasicLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedKeys,setSelectedKeys] = useState<any>(['/']);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  const { initialState, setInitialState } = useModel("@@initialState");
  useEffect(()=>{
    setSelectedKeys([history.location.pathname])
  },[history.location.pathname])
  const handleClick: MenuProps["onClick"] = ({key}) => {
    if (key === "logout") {
      // 调用全局的退出登录方法
      if (initialState?.logout) {
        initialState?.logout();
      }
      // 可选：重置组件的 initialState
      setInitialState({
        ...initialState,
        currentUser: null,
        menuList: []
      } as any);
    }
    if ( key === "user" || key==='admin') {
      const newToken = `role_${key}_token`;
      localStorage.setItem('token', newToken); // 存储新角色 token
      setInitialState({ ...initialState,currentUser: null } as any);
      window.location.reload();
    }
    message.info(`Click on item ${key}`);
  };
  const dropdownMenu: MenuProps = {
    items: [
      // {
      //   key: "profile",
      //   icon: <SmileOutlined />,
      //   label: "个人中心",
      // },
      {
        key: "role",
        icon: <UserSwitchOutlined />,
        label: "角色切换",
        children: [
          {
            key: "user",
            label: "切换user角色",
          },
          {
            key: "admin",
            label: "切换admin角色",
          },
        ],
      },
      {
        key: "logout",
        icon: <LogoutOutlined />,
        label: "退出登录",
      },
    ],
    onClick: handleClick,
  };

  const menuDataRender = (menuData: any):any => {
    return menuData.map(({ icon, children, ...item }: any) => ({
      ...item,
      label: item.name,
      key: item.path,
      // 从图标映射表中获取对应的图标组件
      icon: icon ? iconMap[icon as "smile"] : iconMap["smile"],
      // 递归处理子菜单的图标
      children: children && menuDataRender(children),
    }));
  };
  const menuList = menuDataRender([...staticMenuList,...(initialState?.menuList || [])]);
  const handleMenuClick:MenuProps['onClick']=(e)=>{
    console.log(e.item.props.path)
    const path = e.item.props.path || '/';
    setSelectedKeys([path])
    history.push(path)
  }
  return (
    <Layout className="w-full min-h-screen">
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="h-[40px] text-white flex justify-center items-center border pr-[16px] pl-[24px] m-[4px]">logo</div>
        <Menu
          onClick={handleMenuClick}
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['/']}
          selectedKeys={selectedKeys}
          items={menuList}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
         <Flex justify="space-between" align="center"  className="pr-[24px]">
         <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
           <Dropdown menu={dropdownMenu} trigger={["click"]}>
              <Space className="cursor-pointer">
                <Avatar src={initialState?.currentUser?.avatar} size="small" />
                <span className="ml-[8px]">{initialState?.currentUser?.username}</span>
              </Space>
            </Dropdown>
         </Flex>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
        <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default BasicLayout;